// ************************************************************
// Copyright © 2021
// File Name: main.go
// Author:
// Email:
// Created: 2021-12-19 16:27:34 (CST)
// Last Update:
//          By:
// Description:
// ************************************************************

package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/sync/errgroup"
)

// 用于接收网页自己进行关闭的接口信息传递
var shutdown = make(chan struct{})

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello http Server")
}

func shutDown(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Server stoping...")
	shutdown <- struct{}{}
}

func main() {
	// 初始化和定义webserver路由定义
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", hello)
	mux.HandleFunc("/shutdown", shutDown)

	server := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	g, ctx := errgroup.WithContext(context.Background())

	// 启动web监听协程
	g.Go(func() error {
		return server.ListenAndServe()
	})

	// 启动关闭web协程
	g.Go(func() error {
		select {
		case <-ctx.Done():
			fmt.Println("errgroup exit ...")
		case <-shutdown:
			return server.Shutdown(context.Background())
		}
		return ctx.Err()
	})

	// 启动信号监听协程
	g.Go(func() error {
		exit := make(chan os.Signal)
		signal.Notify(exit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

		select {
		case <-exit:
			fmt.Println("Receive quit signal")
		case <-ctx.Done():
			fmt.Println("errgroup exit ...")
		}

		return server.Shutdown(context.Background())
	})

	fmt.Println("errgroup exit ", g.Wait())
}
